package com.cdplife.ci.modular.system.controller;

import cn.hutool.core.lang.Console;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.cdplife.ci.core.common.annotion.BussinessLog;
import com.cdplife.ci.core.common.annotion.FormToken;
import com.cdplife.ci.core.common.annotion.Permission;
import com.cdplife.ci.core.common.constant.dictmap.InsuranceDict;
import com.cdplife.ci.core.common.constant.state.InsuranceStatus;
import com.cdplife.ci.core.common.exception.BizExceptionEnum;
import com.cdplife.ci.core.log.LogObjectHolder;
import org.springframework.web.bind.annotation.RequestParam;

import com.cdplife.ci.modular.system.model.Insurance;
import com.cdplife.ci.modular.system.model.Policy;
import com.cdplife.ci.modular.system.model.User;
import com.cdplife.ci.modular.system.service.IInsuranceService;
import com.cdplife.ci.modular.system.service.IPolicyService;
import com.cdplife.ci.modular.system.warpper.InsuranceWarpper;

import com.cdplife.ci.core.shiro.ShiroKit;

/**
 * 控制器
 *
 * @author fengshuonan
 * @Date 2018-11-07 14:26:42
 */
@Controller
@RequestMapping("/insurance")
public class InsuranceController extends BaseController {

    private String PREFIX = "/system/insurance/";

    @Autowired
    private IInsuranceService insuranceService;
    
    @Autowired
    private IPolicyService policyService;

    /**
     * 跳转到首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "insurance.html";
    }

    /**
     * 跳转到添加
     */
    @FormToken(save=true)
    @RequestMapping("/insurance_add")
    public String insuranceAdd() {
        return PREFIX + "insurance_add.html";
    }

    /**
     * 跳转到修改
     */
    @FormToken(save=true)
    @RequestMapping("/insurance_update/{insuranceId}")
    public String insuranceUpdate(@PathVariable Integer insuranceId, Model model) {
        Insurance insurance = insuranceService.selectById(insuranceId);
        model.addAttribute("item",insurance);
        LogObjectHolder.me().set(insurance);
        return PREFIX + "insurance_edit.html";
    }
    /**
     * 获取列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
    	List<Map<String, Object>> list = this.insuranceService.selectInsurance(condition);
        return super.warpObject(new InsuranceWarpper(list));
    }

    /**
     * 新增
     */
    @FormToken(remove=true)
    @Permission
    @BussinessLog(value = "添加保险公司", key = "insuranceName,insuranceCode", dict = InsuranceDict.class)
    @RequestMapping(value = "/add")
    @ResponseBody
    public Object add(Insurance insurance) {
    	//校验空字符
        if (ToolUtil.isOneEmpty(insurance.getInsuranceCode(), insurance.getInsuranceName(), insurance.getInsuranceAbbr(),insurance.getCreditCode())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
    	// 判断保险公司代码是否重复
        Insurance theInsurance = insuranceService.getByInsuranceCode(insurance.getInsuranceCode());
        if (theInsurance != null) {
            throw new ServiceException(BizExceptionEnum.INSURANCE_ALREADY_REG);
        }
        
    	//新增获取当前操作者id
    	insurance.setCreatedBy(String.valueOf(ShiroKit.getUser().getId()));
    	
        insuranceService.insert(insurance);
        return SUCCESS_TIP;
    }

    /**
     * 删除保险公司（逻辑删除）
     */
    @Permission
    @BussinessLog(value = "删除保险公司", key = "insuranceName,insuranceCode", dict = InsuranceDict.class)
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Object delete(@RequestParam Integer insuranceId) {
    	if (ToolUtil.isEmpty(insuranceId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        //存在保单的保险公司不能删除。
    	assertAuth(insuranceId);
    	
    	//删除获取当前操作者id
    	Insurance insurance = insuranceService.selectById(insuranceId);
    	insurance.setLastModifiedBy(String.valueOf(ShiroKit.getUser().getId()));
    	insurance.setIsDel(1);
    	insuranceService.updateById(insurance);
        //this.insuranceService.setStatus(insuranceId, InsuranceStatus.DELETED.getCode());
        return SUCCESS_TIP;
    }

    /**
     * 修改
     */
    @FormToken(remove=true)
    @Permission
    @BussinessLog(value = "编辑保险公司", key = "insuranceName,insuranceCode", dict = InsuranceDict.class)
    @RequestMapping(value = "/update")
    @ResponseBody
    public Object update(Insurance insurance) {
    	
    	if (ToolUtil.isEmpty(insurance) || insurance.getId() == null) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
    	
    	// 判断保险公司代码是否重复
        Insurance theInsurance = insuranceService.getByInsuranceCode(insurance.getInsuranceCode());
        if (theInsurance != null) {
        	if(!theInsurance.getId().equals(insurance.getId())) {
        		throw new ServiceException(BizExceptionEnum.INSURANCE_ALREADY_REG);
        	}
        }
        //更新获取当前操作者id作为更新者
    	insurance.setLastModifiedBy(String.valueOf(ShiroKit.getUser().getId()));
    	
        insuranceService.updateById(insurance);
        return SUCCESS_TIP;
    }

    /**
     * 详情
     */
    @RequestMapping(value = "/detail/{insuranceId}")
    @ResponseBody
    public Object detail(@PathVariable("insuranceId") Integer insuranceId) {
        return insuranceService.selectById(insuranceId);
    }
    
    /**
     * 判断当前保险公司是否存在关联保单
     */
	private void assertAuth(Integer insuranceId) {
    	Wrapper<Policy> wrapper = new EntityWrapper<Policy>();
        wrapper = wrapper.eq("insurance_id", insuranceId);
        List<Policy> policys = policyService.selectList(wrapper);
        if (policys == null || policys.size() == 0) {
        	return;
        } else {
        	throw new ServiceException(BizExceptionEnum.CANT_DELETE_INSURANCE);
        }

    }
}
